﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using System.Xml;
using System.Web;
using System.Threading;
using System.Text.RegularExpressions;
using System.Collections.Specialized;
using System.Configuration;
using System.Xml.Linq;

namespace FatusoAction
{
    public class SyncAction
    {
        public static bool Sync(string parametros)
        {
            //As urls com /calendar funcionam, mas as outras jogam pro login

            //Uri.EscapeDataString(
            string login = ConfigurationSettings.AppSettings["LoginEpisodeCalendar"];
            string senha = ConfigurationSettings.AppSettings["SenhaEpisodeCalendar"];
            string siteLoginURL = "http://episodecalendar.com/account/sign_in";
            string siteHomeURL = "http://episodecalendar.com/calendar";
            string siteAllShowsURL = "http://episodecalendar.com/profile/40540/all-shows";
            string siteMyShowsURL = "http://episodecalendar.com/my-shows";

            string siteHomeAnotherMonthURL = "http://episodecalendar.com/profile/40540";

            string xmldatadownloadURL = "http://episodecalendar.com/account/export/episodecalendar-data.xml";

            //====================================
            //Verificar: http://www.pogdesign.co.uk/cat/
            //====================================

            var cookieJar = new CookieContainer();
            CookieAwareWebClient client = new CookieAwareWebClient(cookieJar);

            string response = client.DownloadString(siteLoginURL);
            string token = Regex.Match(response, "authenticity_token.+?value=\"(.+?)\"").Groups[1].Value;
            string siteLoginParams = string.Format("utf8:✓&authenticity_token={2}&user[email]={0}&user[password]={1}user[remember_me]=0&commit=Enter", login, senha, token);
            //WebClient.UploadValues is equivalent of Http url-encode type post
            client.Method = "POST";
            response = client.UploadString(siteLoginURL, siteLoginParams);


            //string response2 = client.DownloadString(siteHomeURL);
            //string response3 = client.DownloadString(siteAllShowsURL);
            //string response4 = client.DownloadString(siteMyShowsURL);
            //token = Regex.Match(response, "authenticity_token.+?value=\"(.+?)\"").Groups[1].Value;
            //siteLoginParams = string.Format("utf8:✓&authenticity_token={2}&user[email]={0}&user[password]={1}user[remember_me]=0&commit=Enter", login, senha, token);
            //string response5 = client.UploadString(siteHomeAnotherMonthURL, siteLoginParams);

            string caminhoDownloadTorrent = ConfigurationSettings.AppSettings["CaminhoDownloadTorrent"].TrimEnd('\\');
            client.DownloadFile(xmldatadownloadURL, caminhoDownloadTorrent + "\\episodecalendar-data.xml");
            //Não Funciona






            //------------------------------------------------
            string cookieHeader;

            //Acessa o site para se logar e recuperar Cookie
            //
            WebRequest loginRequest = WebRequest.Create(siteLoginURL);
            loginRequest.ContentType = "application/x-www-form-urlencoded";
            loginRequest.Method = "POST";
            loginRequest.Credentials = new NetworkCredential(login, senha);
            byte[] loginBytes = Encoding.ASCII.GetBytes(siteLoginParams);
            loginRequest.ContentLength = loginBytes.Length;
            using (Stream os = loginRequest.GetRequestStream()) { os.Write(loginBytes, 0, loginBytes.Length); }
            WebResponse loginResponse = loginRequest.GetResponse();
            cookieHeader = loginResponse.Headers["Set-cookie"];
            //Para ler o conteúdo
            string pagesource;
            using (StreamReader sr3 = new StreamReader(loginResponse.GetResponseStream()))
            {
                pagesource = sr3.ReadToEnd();
            }
            token = Regex.Match(response, "authenticity_token.+?value=\"(.+?)\"").Groups[1].Value;


            //Primeiro Acesso
            //
            string siteListaURL = "http://episodecalendar.com/calendar";
            HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(siteListaURL);
            myRequest.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip,deflate");
            myRequest.Headers.Add("Cookie", cookieHeader);
            myRequest.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
            myRequest.Method = "GET";
            HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();
            StreamReader sr = new StreamReader(myResponse.GetResponseStream());
            cookieHeader = myResponse.Headers["Set-cookie"];
            string result = sr.ReadToEnd();
            sr.Close();
            myResponse.Close();

            //Segundo Acesso
            //
            string siteListaURL2 = "http://episodecalendar.com/profile/40540/all-shows";
            HttpWebRequest myRequest2 = (HttpWebRequest)WebRequest.Create(siteListaURL2);
            myRequest2.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip,deflate");
            myRequest2.Headers.Add("Cookie", cookieHeader);
            myRequest2.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
            myRequest2.Method = "GET";
            HttpWebResponse myResponse2 = (HttpWebResponse)myRequest2.GetResponse();
            StreamReader sr2 = new StreamReader(myResponse2.GetResponseStream());
            string result2 = sr2.ReadToEnd();
            sr2.Close();
            myResponse2.Close();

            ////Acessa o site para recuperar Página de Séries
            //string paginaHTML;
            //string siteListaURL = "http://episodecalendar.com/calendar"; //http://episodecalendar.com/calendar //http://episodecalendar.com/profile/40540/all-shows
            //WebRequest listaRequest = WebRequest.Create(siteListaURL);
            //listaRequest.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip,deflate");
            //listaRequest.Headers.Add("Cookie", cookieHeader);
            //listaRequest
            //WebResponse listaResponse = listaRequest.GetResponse();
            //using (StreamReader sr = new StreamReader(listaResponse.GetResponseStream()))
            //{
            //    paginaHTML = sr.ReadToEnd();
            //}



            loginResponse.Close();
            //listaResponse.Close();
            return true;
        }

        public static bool SyncXML(string parametros)
        {
            //Recupera Séries EpisodeCalendar
            string xmlName = parametros;
            if (xmlName == null || xmlName.Trim() == String.Empty)
                xmlName = ConfigurationSettings.AppSettings["NomeXMLDataEpisodeCalendar"];

            XElement xmlEpiCal = XElement.Load(xmlName);
            List<XElement> episodiosEpiCal = xmlEpiCal.Elements("episode").ToList();
            List<string> seriesEpiCal = new List<string>();
            foreach (XElement episodio in episodiosEpiCal)
                seriesEpiCal.Add(episodio.Element("show").Value.Trim());
            List<string> seriesUnicas = seriesEpiCal.Distinct().ToList();

            #region [Sync Series.xml]
            {
                //Recupera Lista Local
                string SERIES_PATH = ConfigurationSettings.AppSettings["CaminhoXMLSeries"].ToString();
                XElement xmlLocal = XElement.Load(SERIES_PATH);
                List<XElement> episodiosLocal = xmlLocal.Elements("Serie").ToList();
                List<string> seriesLocal = new List<string>();
                foreach (XElement episodio in episodiosLocal)
                    seriesLocal.Add(episodio.Value.Trim());


                //Cria Elementos e Salva Alterações
                string DADOS_PATH = ConfigurationSettings.AppSettings["CaminhoXMLSeries"].ToString();
                XDocument doc = XDocument.Load(DADOS_PATH);
                foreach (string serieEC in seriesUnicas)
                {
                    if (!seriesLocal.Any(s => s.Equals(serieEC, StringComparison.OrdinalIgnoreCase)))
                    {
                        XElement element = new XElement("Serie");
                        element.Add(new XElement("nome", serieEC));
                        element.Add(new XElement("pasta", serieEC));
                        element.Add(new XElement("downloadAuto", "false"));
                        element.Add(new XElement("sinonimos", ""));
                        doc.Root.Add(element);
                    }
                }
                doc.Save(DADOS_PATH);
            }
            #endregion

            #region [Sync SeriesPodnapisi.xml]
            {
                //Recupera Lista Local
                string SERIES_PATH = ConfigurationSettings.AppSettings["CaminhoXMLSeriesPodnapisi"].ToString();
                XElement xmlLocal = XElement.Load(SERIES_PATH);
                List<XElement> episodiosLocal = xmlLocal.Elements("Serie").ToList();
                List<string> seriesLocal = new List<string>();
                foreach (XElement episodio in episodiosLocal)
                    seriesLocal.Add(episodio.Value.Trim());


                //Cria Elementos e Salva Alterações
                string DADOS_PATH = ConfigurationSettings.AppSettings["CaminhoXMLSeriesPodnapisi"].ToString();
                XDocument doc = XDocument.Load(DADOS_PATH);
                foreach (string serieEC in seriesUnicas)
                {
                    if (!seriesLocal.Any(s => s.Equals(serieEC, StringComparison.OrdinalIgnoreCase)))
                    {
                        XElement element = new XElement("Serie");
                        element.Add(new XElement("nome", serieEC));
                        element.Add(new XElement("idPodnapisi", ""));
                        doc.Root.Add(element);
                    }
                }
                doc.Save(DADOS_PATH);
            }
            #endregion


            return true;
        }
    }

}
